package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.MiaoHuiTongUtil;
import com.block.datapush.service.apipush.utils.YongQianFenQiUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 秒汇通
 *
 */
@Service
public class MiaoHuiTongPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);



        if(StrUtil.isEmpty(memberSourceInfo.getRealname())){
            return pushApiResult;
        }
        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5();

        String apiKey = pushApiKeyParam.getApiKey();

        String name = SecureUtil.aes(apiKey.getBytes()).encryptBase64(memberSourceInfo.getRealname());
        String idCard = SecureUtil.aes(apiKey.getBytes()).encryptBase64(memberSourceInfo.getIdcard());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phoneMd5", mobileMd5);
        paramMap.put("name", name);
        paramMap.put("idCard", idCard);
        paramMap.put("city", memberSourceInfo.getCity());
        paramMap.put("money", MiaoHuiTongUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("sex", memberSourceInfo.getSex());
        paramMap.put("age", memberSourceInfo.getAge());
        paramMap.put("sesameScore",MiaoHuiTongUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("device",1);
        paramMap.put("ip",memberSourceInfo.getReqIp());
        paramMap.put("car",MiaoHuiTongUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("house",MiaoHuiTongUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("fund",MiaoHuiTongUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("social",MiaoHuiTongUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        paramMap.put("insurance",MiaoHuiTongUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("businessLicense",0);
        paramMap.put("baiTiao",MiaoHuiTongUtil.getbaitiao(memberSourceInfo.getBaitiao()));
        paramMap.put("huaBei",MiaoHuiTongUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("creditCard",0);
        paramMap.put("credit",MiaoHuiTongUtil.getyuqi(memberSourceInfo.getYuqi()));
        paramMap.put("channelCode",pushApiKeyParam.getApiCode());

        log.info("【秒汇通】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【秒汇通】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String desc = resultObject.getString("desc");

        pushApiResult.setCode(code + "|" );
        pushApiResult.setMessage(desc);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0000")) {
            pushApiResult.setPushSuccess(true);
            return pushApiResult;
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;

    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        String apiKey = pushApiKeyParam.getApiKey();
        String name = SecureUtil.aes(apiKey.getBytes()).encryptBase64(memberSourceInfo.getRealname());
        String idCard = SecureUtil.aes(apiKey.getBytes()).encryptBase64(memberSourceInfo.getIdcard());
        String phone = SecureUtil.aes(apiKey.getBytes()).encryptBase64(memberSourceInfo.getMobile());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", phone);
        paramMap.put("name", name);
        paramMap.put("idCard", idCard);
        paramMap.put("city", memberSourceInfo.getCity());
        paramMap.put("money", MiaoHuiTongUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("sex", memberSourceInfo.getSex());
        paramMap.put("age", memberSourceInfo.getAge());
        paramMap.put("sesameScore",MiaoHuiTongUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("device",1);
        paramMap.put("ip",memberSourceInfo.getReqIp());
        paramMap.put("car",MiaoHuiTongUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("house",MiaoHuiTongUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("fund",MiaoHuiTongUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("social",MiaoHuiTongUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        paramMap.put("insurance",MiaoHuiTongUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("businessLicense",0);
        paramMap.put("baiTiao",MiaoHuiTongUtil.getbaitiao(memberSourceInfo.getBaitiao()));
        paramMap.put("huaBei",MiaoHuiTongUtil.getHuabei(memberSourceInfo.getHuabei()));
        paramMap.put("creditCard",0);
        paramMap.put("credit",MiaoHuiTongUtil.getyuqi(memberSourceInfo.getYuqi()));
        paramMap.put("channelCode",pushApiKeyParam.getApiCode());


        log.info("【秒汇通】导单开始【requestUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【秒汇通】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String desc = resultObject.getString("desc");

        pushApiResult.setCode(code + "|" + desc);
        pushApiResult.setMessage(desc);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0000")) {
            String data = resultObject.getString("data");
            pushApiResult.setApproveUrl(data);
            pushApiResult.setOutOrderNo(memberSourceInfo.getMobileMd5());
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(false);
            pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
            return pushApiResult;
        }
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        JSONObject jsonObject = JSON.parseObject(paramContent);
        String phoneMd5 = jsonObject.getString("phoneMd5");
        noticeParamDTO.setOutOrderNo(phoneMd5);
        noticeParamDTO.setOutFlag(true);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(phoneMd5));
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());

        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "0000");
        jsonObject.put("desc", "success");
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }
}
